<?php

class Workset_Form_Decorator_Attachment extends Zend_Form_Decorator_Abstract {

    const FILEPATH_KEY = 'shortpath';

    const PLACE_ID_KEY = 'place_id';

    const MIMETYPE_KEY = 'mimetype';

    static protected $_helpers = array(
        'picture'   => 'AttachmentPicture',
        'file'      => 'AttachmentFile',
        'swf'       => 'AttachmentSwf'
    );

    static protected $_mimeOptions = array(
        'image/gif'     => 'picture',
        'image/jpeg'    => 'picture',
        'image/png'     => 'picture',
        'image/bmp'     => 'picture',

        'default'       => 'file'
    );

    protected $_placeId = null;

    function render($content) {
        $element = $this->getElement();

        $view    = $element->getView();
        if (null === $view) {
            return $content;
        }

        $options = $this->getOptions();

        if (empty($options['files'])) {
            return $content;
        }

        $placeId = isset($options[self::PLACE_ID_KEY]) && isInt($options[self::PLACE_ID_KEY]) ? $options[self::PLACE_ID_KEY] : null;

        if (null !== $placeId) {
            $file = isset($options['files'][$placeId]) ? $options['files'][$placeId] : null;
        } else {
            $file = $options['files'];
        }

        if (!$file) {
            return $content;
        }

        if (isset($file[self::MIMETYPE_KEY])) {
            $helper = isset(self::$_mimeOptions[ $file[self::MIMETYPE_KEY] ]) ? self::$_mimeOptions[ $file[self::MIMETYPE_KEY] ] : self::$_mimeOptions['default'];
        } else {
            $helper = self::$_mimeOptions['default'];
        }

        $helper = self::$_helpers[$helper];
        $html = $view->{$helper}($file);

        switch ($this->getPlacement()) {
            case self::APPEND:
                return $content.$html;

            case self::PREPEND:
                return $html.$content;

        }

        return $content.$html;
    }

    function setPlaceId($id) {
        $this->_placeId = (int)$id;
    }

    function getPlaceId() {
        return $this->_placeId;
    }

}

?>